package com.ykq.servlet;

import com.ykq.dao.UserDao;
import com.ykq.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/user")
public class UserServlet extends HttpServlet {
    private UserDao userDao=new UserDao();//对象
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码设置
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if("login".equals(method)){
            login(req,resp);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用dao中的方法
        User user=userDao.selectByNameAndPassword(username,password);
        //判断是否登录成功
        if(user!=null){
            //保存到session会话
            req.getSession().setAttribute("user",user);
            //跳转--成功页面【展示所有图书】
            resp.sendRedirect("/book");
        }else{
            //跳转到登录页面
            req.setAttribute("error","<font color='red'>账号或密码错误</font>");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);//转发跳转.必须转发跳转
        }
    }
}
